<template>
    <div class="dhzn_image">

        <!-- 首页首页轮播图 -->
        <div class="d_i-content">

            <!-- 搜索 -->
            <div class="d_i-c-query bcwh p10 mb10 br5 bs1g">
                <el-form :model="acactiveobj" ref="acactiveobj" :rules="rules" label-width="50px" class="d_svcq-form">
                    <el-form-item label='筛选' class="mt10 mb10">
                        <el-col :span='8'>

                            <el-form-item prop="goodsid" class="d_svcq-f-item">
                                <el-select v-model="acactiveobj.goodsid" placeholder="选择查询的首页轮播图" clearable>
                                    <el-option v-for="(item,key) in goodsname" :key='key' :label="item.name" :value="item.id"></el-option>
                                </el-select>
                                
                            </el-form-item>
                        </el-col>
                        <!-- 按钮 -->
                        <el-col :span="13" class="pl10">
                            <el-button type="primary" @click="verification('acactiveobj')" size="medium">搜索</el-button>
                            <el-button type="danger" @click="replacement" size="medium">取消</el-button>
                        </el-col>
                    </el-form-item>
                </el-form>
                <!-- <el-button @click="one">123</el-button> -->
            </div>

            <!-- 列表头部 -->
            <div class="d_i-c-titel bcwh p10 br5 bs1g">
                <span>添加首页轮播图：</span><span @click="dialogaddimg=true,pageingstate=1" class="f24 b00a vm"><i class="el-icon-circle-plus"></i></span>
            </div>

            <div class="d_i-c-list bcwh p10 br5 bs1g">
                <!-- 数据列表 -->
                <table class="d_icl-table tc">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>轮播图</th>
                            <th>所属商品</th>
                            <th>管理</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item,key) in homeacactive" :key="key">
                            <td>{{item.id}}</td>
                            <!-- <td>{{item.imageurl}}</td> -->
                            <td>
                                <el-popover placement="top" popper-class="dh_glp-t-t-popover" trigger="click" v-model="item.visible">
                                    <img :src="item.imageurl">
                                    <img slot="reference" :src="item.imageurl">
                                </el-popover>
                            </td>
                            <td>{{item.goodsid | filgoods}}</td>
                            <td><!--fileList[0].url=item[i]-->
                                <button type="button" @click="dialogacactive=true;for(var i in upactive) i!=='imageurl' ? upactive[i]=item[i] : dialogImageUrl=item[i],upactive.key=key" class="br5 p5 wh bc4a f14"><i class="el-icon-edit"></i>编辑</button>
                                <button type="button" @click="requestdelete(item.id,key)" class="br5 p5 wh bcfd f14">删除<i class="el-icon-close"></i></button>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <!-- 分页 -->
                <div class="d_icl-block mt20">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pagesize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>

            </div>

            <!-- 弹出层 -->
            <el-dialog title="修改首页轮播图" :visible.sync="dialogacactive" width="450px">
                <!-- <span class="ff53 dib mb10">*修改图片必须先删除之前的图片再次上传</span> -->
                <el-form :model="upactive" ref="upactive" label-width="70px" size='mini'>
                    <!-- <el-form-item label="修改首页轮播图" prop="name">
                        <el-input v-model="upactive.name" placeholder="请对首页轮播图重新命名" clearable></el-input>
                    </el-form-item> -->
                    <el-form-item label="修改商品">
                        <el-select v-model="upactive.name" placeholder="选择查询的首页轮播图" clearable>
                            <el-option v-for="(item,key) in goodsname" :key='key' :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="修改图片">
                        <el-upload action="/api/file/upload" ref="upload" name="files" :headers="headers" :limit='1' :on-preview="handlePictureCardPreview" list-type="picture-card" :on-success="uploadimage">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible"><img width="100%" :src="upactive.imageurl" alt=""></el-dialog>
                    </el-form-item>

                    <!-- <el-form-item label="修改描述" prop="description">
                        <el-input type="textarea" v-model="upactive.description" placeholder="请填写新首页轮播图描述" clearable></el-input>
                    </el-form-item> -->
                </el-form>
                <span slot="footer">
                    <el-button @click="dialogacactive=false" size='mini'>取 消</el-button>
                    <el-button type="primary" @click="requestupdata('upactive'),dialogacactive=false" size='mini'>确 定</el-button>
                </span>
            </el-dialog>

            <!-- 添加首页轮播图 -->
            <el-dialog title="添加首页轮播图" :visible.sync="dialogaddimg" width="450px">
                <!-- <span class="ff53 dib mb10">*修改图片必须先删除之前的图片再次上传</span> -->
                <el-form :model="addactive" ref="upactive" label-width="70px" size='mini'>
                    <!-- <el-form-item label="修改首页轮播图" prop="name">
                        <el-input v-model="upactive.name" placeholder="请对首页轮播图重新命名" clearable></el-input>
                    </el-form-item> -->
                    <el-form-item label="修改商品">
                        <el-select v-model="addactive.goodsid" placeholder="选择查询的首页轮播图" clearable>
                            <el-option v-for="(item,key) in goodsname" :key='key' :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="修改图片">
                        <el-upload 
                            action="/api/file/upload" 
                            ref="upload" 
                            name="files" 
                            :headers="headers" 
                            :limit='1' 
                            :on-preview="handlePictureCardPreview" 
                            list-type="picture-card" 
                            :on-success="uploadimage">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible"><img width="100%" :src="addactive.imageurl" alt=""></el-dialog>
                    </el-form-item>

                </el-form>
                <span slot="footer">
                    <el-button @click="dialogaddimg=false" size='mini'>取 消</el-button>
                    <el-button type="primary" @click="requestadd(),dialogaddimg=false" size='mini'>确 定</el-button>
                </span>
            </el-dialog>

        </div>

    </div>
</template>

<script>
import axios from "../../js/request.js"
import login from "../../js/login.js"
let that
export default {
    components: {},
    data() {
        return {
            headers:{},
            active: '',                          //所有的产品
            active: '',                         //全部的首页轮播图
            pageingstate: 0,
            // 查询的绑定对象
            acactiveobj:{
                goodsid: '',
            },
            // 添加首页轮播图
            addactive:{
                imageurl: '',
                goodsid: ''
            },
            // 修改首页轮播图
            upactive:{
                id: '',
                imageurl: '',
                goodsid: '',
                key: ''
            },
            rules:{
                description:[
                    {required:true,message:'请输入首页轮播图',trigger:'change'}
                ],
                goodsid:[
                    {required:true,message:'请选择商品',trigger:'change'}
                ],
                imageurl:[
                    {required:true,message:'请上传首页轮播图的图片',trigger:'blur'}
                ]
            },
            homeacactive: {},
            dialogacactive: false,               //弹出层状态
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,                           //总数据条数
            goodsname:'',
            dialogImageUrl: '',
            dialogVisible: false,
            dialogaddimg: false,                   //添加轮播图的弹出层
            disabled: false,
            fileList: [{name: 'food.jpeg', url: ''}],
            isSuccess: false
        };
    },
    filters:{
        filgoods(id){
            if(that.goodsname !== ''){
                that.goodsname.forEach((item)=>{
                    id === item.id ? id = item.name : '';
                })
                return id
            }
        }
    },
    computed: {},
    watch: {},
    methods: {
        // 单页条数
        handleSizeChange(val) {
            // console.log(`每页: ${val}条数据`);
            this.pagesize = val;
            this.requestimg()
        },

        //分页的跳页函数
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.currentPage = val;
            this.requestimg()
        },

        // 添加活动
        requestadd(){
            // this.$refs[add].validate((valid)=>{
            //     if(valid){
                    // console.log(that.addactive)
                    let data = {};
                    for(var i in that.addactive) data[i] = that.addactive[i];
                    console.log(that.addactive)
                    // let updata = JSON.stringify(data);
                    axios.request("/indexBanner/add","post",data).then(resp=>{
                        console.log(resp)
                        if(resp.data.message === '请求成功'){
                            that.total += 1;
                            data.id = resp.data.data;
                            that.homeacactive.length < that.pagesize ? that.homeacactive.push(data) : '';
                            that.pageingstate = 0;
                            for(var o in that.addactive) that.addactive[o] = '';
                        }else{this.$message.error('添加失败，请重新登录后再次添加')}
                    }).catch( err=> {console.log(err)})
                // }else{this.$message.error('添加失败！请刷新后重新添加！')}
            // })
        },


        // 删除
        requestdelete(id,key){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.request("/indexBanner/delete","post",{id: id}).then( resp=> {
                    // console.log(resp)
                    if(resp.data.message === "请求成功"){
                        that.homeacactive.splice(key,1)
                        that.total--
                        this.$message({
                            type: 'success',
                            message: resp.data.data
                        });
                    }else{this.$message.error('删除失败！请刷新后重新添加！')}
                })
                // .catch( err=>{console.log(err)})
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },

        // 修改首页轮播图
        requestupdata(updata){
            this.$refs[updata].validate((valid)=>{
                if(valid){
                    let data = {};
                    for(var o in that.upactive) o!== 'key' ? data[o] = that.upactive[o] : '';
                    // console.log(data,updata)
                    axios.request("/indexBanner/update","post",data).then( resp=> {
                        console.log(resp)
                        if(resp.data.message === '请求成功'){
                            this.$refs.upload.clearFiles()
                            let key = that.upactive.key;
                            for(var p in data) that.homeacactive[key][p] !== data[p] ? that.homeacactive[key][p]=data[p] : '';
                            that.$message({
                                message: '修改成功',
                                type: 'success'
                            })
                        }else{this.$message.error('修改失败，请尝试重新登录或刷新页面后再次修改！')}
                    }).catch( err=> {console.log(err)})
                }else{return}
            })
        },

        // 查询的验证
        verification(verify){
            this.$refs[verify].validate((valid)=>{
                if(valid){
                    this.requestimg()
                    this.pageingstate = 2;
                }else{return}
            })
        },

        // 取消查询状态
        replacement(){
            this.$refs.acactiveobj.resetFields();
            this.requestimg()
            this.pageingstate = 0;
        },

        // 首页轮播图接口
        requestimg(){
            let that = this;
            let data = {current: that.currentPage,size: that.pagesize};
            for(var i in that.acactiveobj) i !== 'select' && that.acactiveobj[i] !== '' ? data[i] = that.acactiveobj[i] : '';
            axios.request("/indexBanner/list","post",data).then( resp=> {
                // console.log(resp)
                resp.data.data.forEach(item=>{
                    item.visible = false;
                }) 
                that.homeacactive = resp.data.data;
                that.total = resp.data.code;
                if(that.pageingstate === 2){
                    resp.data.code !== 0 ?(
                        this.$message({
                            message: '为您找到'+resp.data.code+'条首页轮播图',
                            type: 'success'
                        })
                    ) : this.$message('没有符合条件的首页轮播图')
                }
                // console.log(that.homeacactive,data)
            }).catch( err=> {console.log(err)})
        },

        // 上传本地图片
        uploadimage(response, file, fileList){
            console.log(response,'2',that.dialogImageUrl,'3',that.addactive.imageurl)
            if(this.pageingstate!==1){
                this.upactive.imageurl = 'http://dzy.dpyun.site/upload/images/' + response.data[0]
            }else{
                this.addactive.imageurl = 'http://dzy.dpyun.site/upload/images/' + response.data[0]
            }     
        },

        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

        // 拿商品
        requestgoods(){
            axios.request("/goods/list","post",{current:1,size:10000000}).then( resp=> {
                console.log(resp)
                this.goodsname = resp.data.data.map((item)=>{
                    return{
                        id: item['id'],
                        name: item['name']
                    }
                })
            })
        },
        
        //拿token
        newtoken(){
            let that = this;
			let axios = require('axios')
            let Base64 = require('js-base64').Base64;
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
            login.login("/getAuthority/manager","post",data).then( resp=> {
                console.log(resp)
                that.token = resp.data.data;
                sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                // console.log(that.token,that.headers)
                this.requestimg()
                sessionStorage.getItem("goodsdata") !== null 
                    ? this.goodsname = JSON.parse(sessionStorage.getItem("goodsdata")) 
                    : this.requestgoods();
                that.headers = {
                    'Conente-Type': 'application/json',
                    'authorization': `Bearer ${resp.data.data}`
                }
                // let one1 = Base64.encode(data.username)
                // let two2 = Base64.encode(that.token)
                // console.log(one1,Base64.decode(one1),Base64.decode(one))
                // console.log(two2,Base64.decode(two2),Base64.decode(two))
			}).catch( err=> {console.log(err)})
        },
        
    },
    created() {},
    mounted() {
        this.newtoken()
        // this.$nextTick(function() {
        //     this.requestimg()
        // });
    },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dhzn_image{
    height: calc(100% - 56px);
    box-sizing: border-box; 
}
.d_i-content{
    height: 100%;
}
/* 搜索 */
.d_svcq-f-item .el-select{
    width: 100%;
}
.d_i-c-list{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 158px);
}
/* 表单样式 */
.d_icl-table{
    width: 100%;
    color: #666666;
    border-bottom: 1px solid #e0e0e0;
    border-left: 1px solid  #e0e0e0;
    border-collapse: collapse; 
}
.d_icl-table thead tr,.d_icl-table tbody tr:hover{
    background-color: #F2F2F2;
}
.d_icl-table th, .d_icl-table td{
    min-height: 50px;
    padding: 10px;
    border-top: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
}
.d_icl-table tr td img{
    max-width: 120px;
    max-height: 80px;
}

/* 图片大小的 */
/* 左边的图片预览效果 */
.dh_glp-t-t-popover img{
    max-width: 500px;
    max-height: 500px;
}
</style>